<template>
<!--  模块管理-->
   <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div class="structure_cent_b">
          <div class="structure_cent_b_left">
                   <a-tree :tree-data="bumentreeData"  :replaceFields='replaceFields' @select='clicktree' :default-selected-keys="defaultselected"  ></a-tree>

          </div>
           <div class="structure_cent_b_right">
        <div class="structure_cent_b_title">
          <a-button   v-action:add type='primary' @click="adddepartment1">新增</a-button>
          <a-button   v-action:edit type='primary' style="margin-left:20px;" @click="bianji">编辑</a-button>
          <a-button   v-action:assigningRoles type='primary' style="margin-left:20px;" @click="fenpeijuese(1)">分配角色</a-button>

                <a-popconfirm
                  style="margin-left:20px;"
                  cancelText='取消'
                  okText="确认"
                  title="您确定要删除吗?"
                  @confirm="shanchu()"
                >
                  <!-- <a href="javascript:;">删除</a> -->
                   <a-button  v-action:del type='danger'>删除</a-button>
                </a-popconfirm>
        </div>
          <a-table :columns="columns" :data-source="datalist" bordered  :rowKey='record=>record.id' :pagination="false" :childrenColumnName="'childList'">
             <template slot="source" slot-scope="text">
               {{sourcearr[text].name}}
             </template>
   
              <template slot="操作" slot-scope="text, record">
                  <a  v-action:assigningRoles  href="javascript:;" @click="fenpeijuese(record)" style="margin-left:20px">分配角色</a>

                <a-popconfirm
                  style="margin-left:20px"
                  cancelText='取消'
                  okText="确认"
                  title="您确定要删除吗?"
                  @confirm="onDelete(record)"
                >
                  <a  v-action:del  href="javascript:;">删除</a>
                </a-popconfirm>
              </template>

           </a-table> 

      </div>
        </div>
      </div>

       <!-- 新增 -->
    <a-modal :title="usertitle" :visible="visible1" :confirm-loading="confirmLoading1" @ok="tijiaobumen" @cancel="handleCancel" :destroyOnClose='true' cancel-text="取消" ok-text="确定">
        <a-form :form="bumenform" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="tijiaobumen">

            <a-form-item label="模块名称">
              <a-input
                placeholder="请输入模块名称"
                v-decorator="['name', { rules: [{ required: true, message: '请输入模块名称' }] }]"
              />
            </a-form-item>
            <a-form-item label="来源类型">
              <a-select
                      v-decorator="[
                        'source',
                        { rules: [{ required: true, message: '请选择来源类型' }] },
                      ]"
                      placeholder="请选择来源类型">
                      <a-select-option v-for="(item,i) in sourcearr" :key="i" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
            </a-form-item>
            <a-form-item label="跳转地址" >
              <a-input
                placeholder="请输入跳转地址"
                v-decorator="['webUrl', { rules: [{ required: false, message: '请输入跳转地址' }] }]"
              />
            </a-form-item>
            <a-form-item label="模块排序" >
              <a-input
                placeholder="请输入模块排序"
                v-decorator="['orderNum', { rules: [{ required: true, message: '请输入模块排序' }] }]"
              />
            </a-form-item>
            <a-form-item label="模块状态" >
              <a-select
                      v-decorator="[
                        'status',
                        { rules: [{ required: true, message: '请选择模块状态' }] },
                      ]"
                      placeholder="请选择模块状态">
                      <a-select-option v-for="(item,i) in statusarr" :key="i" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
            </a-form-item>
            <a-form-item label="模块类型" >
              <a-select
                      v-decorator="[
                        'type',
                        { rules: [{ required: true, message: '请选择模块状态' }] },
                      ]"
                      placeholder="请选择模块状态">
                      <a-select-option v-for="(item,i) in typearr" :key="i" :value="item.id">{{item.name}}</a-select-option>

                    </a-select>
            </a-form-item>
            <!-- <a-form-item label="选择上级" >
                <a-tree-select
                  v-decorator="[
                    'parentId',
                    { rules: [{ required: false, message: '请选择上级' }] },
                  ]"
                  style="width: 100%"
                  :tree-data="bumentreeData"
                  placeholder="请选择上级"
                  :show-checked-strategy="SHOW_PARENT"
                  :replaceFields='replaceFields'
                  @change='selectgongsitree'
                />
            </a-form-item> -->
            <a-form-item label="上传图片">
                    <UploadImg @returndata='huidiao' :file='fileList' :num='1'/>
            </a-form-item>
          </a-form>
    </a-modal>
    <!-- 分配 -->
    <a-modal :title="usertitle" :visible="visible" :confirm-loading="confirmLoading" @ok="tijiaobumen1" @cancel="handleCancel" :destroyOnClose='true' cancel-text="取消" ok-text="确定">
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="tijiaobumen1">
            <a-form-item label="模块名称">
                <a-input v-model="xuanzhongarr[0].name" :disabled='true'/>
            </a-form-item>
            <a-form-item label="选择菜单" v-if='usertitle=="分配菜单"'>
                <a-tree-select
                  v-decorator="[
                    'detpIds',
                    { rules: [{ required: true, message: '请选择菜单' }] },
                  ]"
                  style="width: 100%"
                  :tree-data="caidanData"
                  tree-checkable
                  :treeCheckStrictly='true'
                  placeholder="请选择菜单"
                  :replaceFields='replaceFields'
                  @change='selectusertree'
                />
            </a-form-item>
            <a-form-item label="选择角色" v-if='usertitle=="分配角色"'>
                <a-select
                    mode="multiple"
                    placeholder="请选择角色"
                    v-decorator="['roleIds', { rules: [{ required: true, message: '请选择角色' }] }]"
                >
                <a-select-option v-for="item in jueseData" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
            </a-form-item>
          </a-form>
    </a-modal>
    </a-card>
   </page-header-wrapper>
</template>
<script>
import {getTree,sava,deletemodule,get,caidanTree,jueseTree,fenpeijuesea,mokuaijuese} from '@/api/modulement'
import { TreeSelect } from 'ant-design-vue';
import {getTreeData,getchild,urls} from '@/utils/util'
import UploadImg from '@/views/component/uploadimg'
import { values } from 'mockjs2';

const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const columns = [
  
  {
    title: '排序',
    dataIndex: 'orderNum',
    align:'center'
  },
  {
    title: '模块名称',
    dataIndex: 'name',
    align:'center'
  },
  {
    title: '模块来源',
    dataIndex: 'source',
    align:'center',
    scopedSlots: { customRender: 'source' },

  },
  {
    title: '跳转地址',
    dataIndex: 'webUrl',
    align:'center'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: '操作' },
    align:'center'
  },
];
export default {
  data(){
    return{
      xuanzhongarr:[{
        name:''
      }],
      jueseData:[],
      caidanData:[],
      fileList:[],
      SHOW_PARENT,
      confirmLoading1:false,
      visible1:false,
      confirmLoading:false,
      visible:false,
      replaceFields:{
          children:'childList',
          title:'name',
          key:'id',
          value:'id'
      },
      usertitle:'',
      datalist:[],
      treeData:[],
      bumentreeData:[],
      bianjitype:0,
      columns,
      bianjiId:'',
      defaultselected:[],

      form: this.$form.createForm(this, { name: 'coordinated' }),
      bumenform: this.$form.createForm(this, { name: 'coordinated1' }),
      userarr:[],
      typeId:0,
      bumenarr:'',
      yingjilist:[
        {id:0,name:'公司'},
        {id:1,name:'部门'}
      ],
      statusarr:[
        {id:0,name:'显示'},
        {id:1,name:'不显示'}
      ],
      typearr:[
        {id:0,name:'客户端'},
        {id:1,name:'模块'}
      ],
      sourcearr:[
        {id:0,name:'后台系统管理'},
        {id:1,name:'H5端'},
        {id:2,name:'安卓'},
        {id:3,name:'苹果'},
        {id:4,name:'PC端'},
        {id:5,name:'微信小程序'},
        {id:6,name:'商家端'},
      ]
    }
  },
  mounted(){
    this.getbumenTree()
  },
  components:{
    UploadImg
  },
  methods:{

    //获取公司部门树
    getbumenTree(){
        new Promise((resolve, reject) => {
          getTree().then(response => {
              console.log(response);
              if(response.code==0){
                this.bumentreeData=response.data.records
                // this.defaultselected=[]
                // this.defaultselected.push(
                //   this.bumentreeData[0].id
                // )
                this.datalist=this.bumentreeData
                // this.xuanzhongarr=getTreeData(this.defaultselected,this.bumentreeData)

                console.log(this.defaultselected);
                // this.clicktree(this.defaultselected)
              }else{
                  this.$notification.error({
                  message: '失败',
                description: response.msg,
                  })
              }
              resolve()
          }).catch(error => {
              // this.$notification.error({
              // message: '失败',
              // description: `获取失败`
              // })
              reject(error)
          })
        })
    },
    //点击人组织架构树
    clicktree(val,e){
      console.log('值',val);
      if(val.length){
        this.defaultselected=[]
          this.defaultselected.push(
            val[0]
          )
        this.xuanzhongarr=getTreeData(this.defaultselected,this.bumentreeData)
        this.datalist= this.xuanzhongarr[0].childList
        console.log(this.xuanzhongarr);
        console.log(this.defaultselected);
      }else{
         this.xuanzhongarr=[{name:''}]
        this.datalist=this.bumentreeData
      }
    },

    //删除
    onDelete(val){
          new Promise((resolve, reject) => {
            deletemodule({id:val.id}).then(response => {
                if(response.code==0){
                    this.getbumenTree()
                    this.$notification.success({
                    message: '成功',
                    description: '删除成功'
                    })
                }else{
                    this.$notification.error({
                    message: '失败',
                    description: response.msg
                    })
                }
                resolve()
            }).catch(error => {
                this.$notification.error({
                message: '失败',
                description: `查询失败`
                })
                reject(error)
            })
          })
    },
    shanchu(){
      console.log(this.xuanzhongarr);
      if(this.xuanzhongarr[0].name){
          new Promise((resolve, reject) => {
            deletemodule({id:this.xuanzhongarr[0].id}).then(response => {
                if(response.code==0){
                    this.getbumenTree()
                    this.$notification.success({
                    message: '成功',
                    description: '删除成功'
                    })
                }else{
                    this.$notification.error({
                    message: '失败',
                    description: response.msg
                    })
                }
                resolve()
            }).catch(error => {
                this.$notification.error({
                message: '失败',
                description: `查询失败`
                })
                reject(error)
            })
          })
      }else{
                        this.$notification.error({
                message: '失败',
                description: `请选择你要删除的模块`
                })
      }

    },
    //编辑
    bianji(){
      console.log(this.xuanzhongarr);
      if(this.xuanzhongarr[0].name){
      this.bianjitype=1
      this.usertitle='编辑'
      this.typeId=this.xuanzhongarr[0].type
      this.bianjiId=this.xuanzhongarr[0].id
         new Promise((resolve, reject) => {
            get({id:this.bianjiId}).then(response => {
                if(response.code==0){
                  console.log(response);
                  this.visible1 = true;
                  this.$nextTick(()=>{
                      this.bumenform.setFieldsValue({
                        name:response.data.name ,
                        webUrl:response.data.webUrl,
                        orderNum:response.data.orderNum,
                        source:response.data.source,
                        status:response.data.status,
                        type:response.data.type,
                        parentId:response.data.parentId==0?'':response.data.parentId,
                      });
                  })
                  this.fileList=[]
                  if(response.data.logoUrl){
                  this.fileList.push(
                    {
                      uid:-1,
                      url:urls+response.data.logoUrl,
                      urlimg:response.data.logoUrl,
                      status: 'done',
                    }
                    )
                    console.log(this.fileList);
                  }

                }else{
                    this.$notification.error({
                    message: '失败',
                    description: response.msg
                    })
                }
                resolve()
            })
          })
      }else{
                this.$notification.error({
                message: '失败',
                description: `请选择数据`
                })
      }
 
    },
    //选择人员树
    selectusertree(value, label, extra){
      console.log('人员',value, label, extra);
      this.userarr=[]
      let userid=[]
      if(value.length!=0){
        value.forEach(item => {
          userid.push(item.value)
        });
      this.userarr=getTreeData(userid,this.treeData)
      }
      console.log(this.userarr);
    },

    //新增
    adddepartment1(){
      this.usertitle='新增'
      this.fileList=[]
      this.visible1 = true;
      this.bianjitype=0
      this.$nextTick(()=>{
          this.bumenform.setFieldsValue({
            status:0,
          });
      })

    },
    //选择部门树
    selecttree(value, label, extra){
      this.bumenarr=''
      let arr=[]
      arr.push(value)
      console.log('部门',value);
      console.log('部门',arr);
      this.bumenarr=getTreeData(arr,this.bumentreeData)
      console.log(this.bumenarr);
    },
    //分配角色
    fenpeijuese(val){
      console.log(val);
      this.usertitle="分配角色"
      if(this.xuanzhongarr[0].name&&val==1){
        this.bianjiId=this.xuanzhongarr[0].id
        this.getjuselist()
        this.getidjuselist(this.bianjiId)
      }else if(val!=1){
        console.log(val);
        this.xuanzhongarr=[]
        this.xuanzhongarr.push(val)
        this.bianjiId=val.id
        this.getjuselist()
        this.getidjuselist(this.bianjiId)
      }else{
          this.$notification.error({
          message: '失败',
          description: `请选择数据`
          })
      }
    },
    //根据ID获取角色列表
    getidjuselist(val){
      new Promise((resolve, reject) => {
            mokuaijuese({id:val}).then(response => {
                if(response.code==0){
                  console.log(response);
                  this.visible=true
                  if(response.data.length!=0){
                   let data=[]
                    response.data.forEach(item=>{
                      data.push(item.id)
                    })
                    this.$nextTick(()=>{
                        this.form.setFieldsValue({
                        roleIds:data ,
                        });
                    })
                    
                  }
                }else{
                    this.$notification.error({
                    message: '失败',
                    description: response.msg
                    })
                }
                resolve()
            }).catch(error => {
                this.$notification.error({
                message: '失败',
                description: `查询失败`
                })
                reject(error)
            })
        })
    },
    //获取角色列表
    getjuselist(){
      new Promise((resolve, reject) => {
            jueseTree().then(response => {
                if(response.code==0){
                  console.log(response);
                  this.jueseData=response.data
                }else{
                    this.$notification.error({
                    message: '失败',
                    description: response.msg
                    })
                }
                resolve()
            }).catch(error => {
                this.$notification.error({
                message: '失败',
                description: `查询失败`
                })
                reject(error)
            })
        })
    },
    //选择公司树
    selectgongsitree(value, label, extra){
      this.bumenarr=''
      let arr=[]
      arr.push(value)
      console.log('公司',value);
      console.log('公司',arr);
      this.bumenarr=getTreeData(arr,this.treeData)
      console.log(this.bumenarr);
    },
    //提交分配
    tijiaobumen1(e){
      e.preventDefault();
      this.form.validateFields((err,values)=>{
        if(!err){
          console.log(values);
          console.log(this.bianjiId);
          this.confirmLoading=true
          if(this.usertitle=='分配菜单'){
              let arr=[]
              values.detpIds.forEach((item)=>{
                console.log(item);
                arr.push(item.value)
              })
              new Promise((resolve, reject) => {
                    fenpeicaidan({id:this.bianjiId,menuIds:arr.join(',')}).then(response => {
                        if(response.code==0){
                          console.log(response);
                          this.confirmLoading=false
                          this.visible=false
                            this.$notification.success({
                            message: '成功',
                            description: '分配成功'
                            })
                        }else{
                          this.confirmLoading=false
                            this.$notification.error({
                            message: '失败',
                            description: response.msg
                            })
                        }
                        resolve()
                    }).catch(error => {
                        this.confirmLoading=false
                        this.$notification.error({
                        message: '失败',
                        description: `提交失败`
                        })
                        reject(error)
                    })
                })
          }else if(this.usertitle=='分配角色'){
              let arr=[]
              values.roleIds.forEach((item)=>{
                arr.push(item)
              })
              console.log(arr);
              new Promise((resolve, reject) => {
                    fenpeijuesea({id:this.bianjiId,roleIds:arr.join(',')}).then(response => {
                        if(response.code==0){
                          console.log(response);
                          this.confirmLoading=false
                          this.visible=false
                            this.$notification.success({
                            message: '成功',
                            description: '分配成功'
                            })
                        }else{
                          this.confirmLoading=false
                            this.$notification.error({
                            message: '失败',
                            description: response.msg
                            })
                        }
                        resolve()
                    }).catch(error => {
                        this.confirmLoading=false
                        this.$notification.error({
                        message: '失败',
                        description: `提交失败`
                        })
                        reject(error)
                    })
                })
          }

        }
      })
    },
    //提交新增
    tijiaobumen(e){
      e.preventDefault();
      this.bumenform.validateFields((err, values) => {
          if(!err){
            console.log(values);
            console.log(this.fileList);
            let data
            console.log(this.fileList.length);
              if(this.fileList.length&&this.bianjitype==0){        
                data={
                  name:values.name,
                  orderNum:values.orderNum,
                  parentId:values.parentId,
                  status:values.status,
                  type:values.type,
                  webUrl:values.webUrl,
                  source:values.source,
                  logoUrl:this.fileList[0].response.data.url
                }
              }else{
                data={
                  name:values.name,
                  orderNum:values.orderNum,
                  parentId:values.parentId,
                  status:values.status,
                  type:values.type,
                  source:values.source,
                  webUrl:values.webUrl,
                }
              }
            if(this.bianjitype==0){

                new Promise((resolve, reject) => {
                  sava(data).then(response => {
                      if(response.code==0){
                          this.$notification.success({
                          message: '成功',
                          description: '操作成功'
                          })
                        this.getbumenTree()
                        this.confirmLoading1=false
                        this.visible1 = false;
                        console.log(response);
                      }else{
                        this.confirmLoading1=false
                        this.visible1 = false;
                          this.$notification.error({
                          message: '失败',
                          description: response.msg
                          })
                      }
                      resolve()
                  }).catch(error => {
                      this.$notification.error({
                      message: '失败',
                      description: `查询失败`
                      })
                      reject(error)
                  })
                })
            }else{
              let usrsrc;
              if(this.fileList.length){
                if(this.fileList[0].response){
                  usrsrc=this.fileList[0].response.data.url
                  data.logoUrl=usrsrc
                  data.id=this.bianjiId
                }else{
                  usrsrc=this.fileList[0].urlimg
                  data.logoUrl=usrsrc
                  data.id=this.bianjiId
                }
              }else{
                  data.id=this.bianjiId
              }

                new Promise((resolve, reject) => {
                  sava(data).then(response => {
                      if(response.code==0){
                          this.$notification.success({
                          message: '成功',
                          description: '操作成功'
                          })
                        this.getbumenTree()
                        this.confirmLoading1=false
                        this.visible1 = false;
                        console.log(response);
                      }else{
                        this.confirmLoading1=false
                        this.visible1 = false;
                          this.$notification.error({
                          message: '失败',
                          description: response.msg
                          })
                      }
                      resolve()
                  }).catch(error => {
                      this.$notification.error({
                      message: '失败',
                      description: `查询失败`
                      })
                      reject(error)
                  })
                })
            }


          }



      })
    },
    //取消弹窗
    handleCancel(e) {
      this.confirmLoading1=false
      this.visible1 = false;
      this.confirmLoading=false
      this.visible = false;
    },
        //回调
        huidiao(v){
            console.log(v);
            this.fileList=v
            console.log(this.fileList);
        },
  }
}
</script>

<style scoped>
.structure_cent{
  background: #fff;
  border: 1px solid #ccc;
}
.structure_cent_title{
  width: 100%;
  font-size: 16px;
  color: #333;
  background: #f6f6f6;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
}
.structure_cent_title span{
  border-left: 4px solid #0086ff;
  padding-left: 15px;
}
.structure_cent_b{
  max-width: 1200px;
  margin: auto;
  /* padding-top: 60px;
  padding-bottom: 60px; */
  display: flex;
  justify-content: space-between;
}
.structure_cent_b_left{
  width: 300px;
  border: 1px solid #ccc;
}
.structure_cent_b_right{
  width: 800px;
  margin-left: 20px;
}
.structure_cent_b_title{
  margin-bottom: 30px;
}
.addbtn_f{
  width: 400px;
  display: flex;
  justify-content: space-between;
}
.addbtn_f div{
  width: 100px;
  height: 35px;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 35px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background: #f2f2f2;
}

.addbtn_f div:hover{
  background: #0086ff;
  color: #fff;
}
</style>